package com.leetcode.search.dfs;

/**
 * @author Dennis Li
 * @date 2020/10/20 20:11
 */
public class WordSearch_79 {

    public boolean exist(char[][] board, String word) {
        int high = board.length, width = board[0].length;
        boolean[][] visited = new boolean[high][width];

        for (int i = 0; i < high; i++)
            for (int j = 0; j < width; j++)
                if (board[i][j] == word.charAt(0) && dfs(board, word, 0, i, j, visited))
                    return true;

        return false;
    }

    private boolean dfs(char[][] board, String word, int index, int i, int j, boolean[][] visited) {
        if (index == word.length()) {
            return true;
        }

        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length
                || visited[i][j] || board[i][j] != word.charAt(index)) {
            return false;
        }

        visited[i][j] = true;
        if (dfs(board, word, index + 1, i + 1, j, visited) ||
                dfs(board, word, index + 1, i - 1, j, visited) ||
                dfs(board, word, index + 1, i, j + 1, visited) ||
                dfs(board, word, index + 1, i, j - 1, visited)) {
            return true;
        }
        visited[i][j] = false;
        return false;
    }

}
